/*
 * Filename : PieChartWithCustomColours.java
 * Description : **COMPLETE**
 * History  : Date               Engineer       Description
 *            ---------          ------------   --------------------------------
 *            September 18, 2007      waitek         Initial creation.
 */

package com.lct.eq2.gui;

import java.awt.Color;
import java.io.File;
import java.util.List;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;

public class PieChartWithCustomColours {
    public static void main(String[] args) {
        DefaultPieDataset dataset = new DefaultPieDataset();
        JFreeChart chart;
       
        // Defining the dataset
        dataset.setValue("Windows", 60);
        dataset.setValue("Linux", 20);
        dataset.setValue("Mac", 10);
        dataset.setValue("Unix", 5);
        dataset.setValue("DOS", 5);
       
        chart = ChartFactory.createPieChart(
                "OS Chart", // chart title
                dataset,    // chart data
                true, 
                true, 
                true);
       
        PiePlot plot = (PiePlot)chart.getPlot();
       
        // Specify the colors here
        Color[] colors = {Color.blue, Color.yellow, Color.green};
        PieRenderer renderer = new PieRenderer(colors);
        renderer.setColor(plot, dataset);
       
        try
        {
            // This will create a PNG image
            ChartUtilities.saveChartAsPNG(new File("chart.png"), chart, 400,
                    220);
        }
        catch (Exception e)
        {
            System.out.println("Exception while creating the chart");
        }
    }
   
   
    /*
     * A simple renderer for setting custom colors
     * for a pie chart.
     */
   
    public static class PieRenderer {
        private Color[] color;
       
        public PieRenderer(Color[] color) {
            this.color = color;
        }       
       
        public void setColor(PiePlot plot, DefaultPieDataset dataset) {
            List <Comparable> keys = dataset.getKeys();
            int aInt;
           
            for (int i = 0; i < keys.size(); i++) {
                aInt = i % this.color.length;
                plot.setSectionPaint(keys.get(i), this.color[aInt]);
            }
        }
    }
    
}
